package com.yg.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yg.item.mapper.CategoryMapper;
import com.yg.item.pojo.ItemType;
import com.yg.item.pojo.vo.OneCategory;
import com.yg.item.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, ItemType> implements CategoryService {
    @Override
    public List<OneCategory> getAllCategory() {
        //查询所有一级分类  parent=0
        QueryWrapper<ItemType> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("level", "1");
        List<ItemType> oneCategoryList = baseMapper.selectList(wrapperOne);
        //查询所有二级分类  parent != 0
        QueryWrapper<ItemType> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.eq("level","2");
        List<ItemType> twoCategoryList = baseMapper.selectList(wrapperTwo);

        //创建list 集合用于存储最终封装数据
        List<OneCategory> finalSubjectList = new ArrayList<>();
        for (int i = 0; i < oneCategoryList.size() ; i++) {
            ItemType itemType = oneCategoryList.get(i);
            OneCategory oneCategory = new OneCategory();
            BeanUtils.copyProperties(itemType,oneCategory);

            finalSubjectList.add(oneCategory);


            //创建list集合封装每个一级分类的二级分类
            List<ItemType> twoFinalSubjectList = new ArrayList<>();
            for (int j = 0; j < twoCategoryList.size(); j++) {
                ItemType twoItemType = twoCategoryList.get(j);
                //判断二级分类parent是否与一级分类id一致
                if (twoItemType.getParent().equals(itemType.getId())){
                    ItemType twoCategory = new ItemType();
                    BeanUtils.copyProperties(twoItemType,twoCategory);
                    twoFinalSubjectList.add(twoCategory);
                }
            }
            oneCategory.setChildren(twoFinalSubjectList);
        }



        return finalSubjectList;
    }
}
